<?php
namespace Manage\Model;
use Think\Model;
use Common\Library\Category;
class CategoryModel extends Model{
	/**
	 * 添加或修改
	 */
	public function operCategory($data,$category_id=0){
		$cate_data=$this->data($data)->create();
		$cate_data['date_modified']=time();
		if($category_id){		
			$this->where(array('category_id'=>$category_id))->save($cate_data);
		}else{
			$cate_data['date_added']=time();
			$category_id=$this->add($cate_data);
		}
		$CategoryDescriptionModel=M('CategoryDescription');
		$map=array(
			'category_id'	=>	(int)$category_id
			);
		$CategoryDescriptionModel->where($map)->delete();
		foreach ($data['category_description'] as $language_id => $category_description) {
			$category_description['language_id']=$language_id;
			$category_description['category_id']=$category_id;
			$CategoryDescriptionModel->add($category_description);
		}
	}
	public function getCategory($category_id=0){
		$map=array('category_id'=>(int)$category_id);
		$category=$this->where($map)->find();
		$cd=M('CategoryDescription')->where($map)->select();
		foreach ($cd as $v) {
			$category['category_description'][$v['language_id']]=$v;
		}
		return $category;
	}
	/**
	 * 获取分类列表
	 */
	public function getCategories($data=array()){
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		$order='sort_order '. (isset($data['order'])?$data['order']:'ASC');
		$order .= ',category_id DESC';
		if(isset($data['category_id'])) $map[C('DB_PREFIX').'category.category_id']=array('neq',$data['category_id']);
		if(isset($data['status'])) $map['status']=$data['status'];
		if(isset($data['title'])) $map['title'] = array('like',"%".$data['title']."%");
		$categories=$this->join('LEFT JOIN  __CATEGORY_DESCRIPTION__ ON __CATEGORY__.category_id=__CATEGORY_DESCRIPTION__.category_id')->where($map)->field(C('DB_PREFIX')."category.category_id,title,parent_id,image,status")->order($order)->select();
		return $categories;
	}
	public function getChildId($category_id){
		$cate=$this->select();
		$cate_ids=Category::getChildsId ($cate, $category_id,"category_id","parent_id");
		$cate_ids=array_merge(array($category_id),$cate_ids);		
		return $cate_ids;
	}

	public function del($category_id){
		$return=0;
		$map['category_id']=array('in',$this->getChildId($category_id));
		$return=$this->where($map)->delete();
		M('CategoryDescription')->where($map)->delete();
		return $return;
	}
}